package com.fjzx.androidframe.base.adapter;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 基础ViewPager适配器
 *
 * @param <T>
 * @author xiongyongcong
 */
public abstract class BasePagerAdapter<T, V extends View> extends PagerAdapter {
    /**
     * 数据
     **/
    private List<T> mData = new ArrayList<>();
    /**
     * View
     **/
    private List<V> mViews;

    public BasePagerAdapter(List<V> views) {
        this.mViews = views;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = mViews.get(position % mViews.size());
        bindViewData(view, position, mData.get(position));
        container.addView(view);
        return view;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    /**
     * 绑定数据
     *
     * @param data
     */
    public void setData(List<T> data) {
        mData.addAll(data);
        notifyDataSetChanged();
    }

    /**
     * 清除原数据并绑定新数据
     *
     * @param data
     */
    public void clearAndSetData(List<T> data) {
        mData.clear();
        mData.addAll(data);
        notifyDataSetChanged();
    }

    /**
     * 子类重写此方法，完成数据绑定
     *
     * @param view
     * @param position
     * @param data
     */
    abstract protected void bindViewData(View view, int position, T data);
}
